package com.citywithincity.db.data2entity;

import java.lang.reflect.Field;

import com.citywithincity.db.BindConvert;
import com.citywithincity.db.annotation.ColumnConvert;
import com.citywithincity.db.interfaces.IValueConvert;
import com.citywithincity.db.interfaces.SqlDriver;
import com.citywithincity.utils.CachedClassUtil;
import com.citywithincity.utils.ClassUtil;
import com.damai.utils.value.ValueConvertFactory;

public class Data2EntityCreator {
	

	/**
	 * 
	 * @param field				实体类的class
	 * @param columnClass		数据库字段的class
	 * @param driver			数据库驱动
	 * @return
	 * @throws Exception 
	 */
	public static IValueConvert createEntityConver(Field field, Class<?> columnClass,SqlDriver driver){
		ColumnConvert convert = field.getAnnotation(ColumnConvert.class);
		Class<?> targetClass = field.getType();
		if(convert!=null){
			targetClass = convert.target();
		}
		try{
			IValueConvert valueConvert = driver.create(columnClass, targetClass);
			if(valueConvert==null){
				valueConvert = ValueConvertFactory.create(columnClass, targetClass);
			}
			return createValueConver(valueConvert, convert);
		}catch(Exception e){
			throw new RuntimeException(e);
		}
		
	}
	

	
	



	/**
	 * try{
			
			IValueConvert valueConvert = null;
			ClassUtil.isEqual(targetClass,columnClass);
			if(!ClassUtil.isEqual(columnClass, targetClass)){
				valueConvert=create(field,columnClass,targetClass,driver);
			}
			if(convert!=null){
				return createValueConver(valueConvert,convert.toEntity());
			}
			return valueConvert;
		}catch (Exception e) {	
			throw new RuntimeException("Class "+field.getDeclaringClass()+" field "+field.getName()+" data convert:"+e.getMessage(),e);
		}
	 */
	
	/**
	 * 
	 * @param from
	 *            输入不可能有byte[]
	 * @param to
	 * @return
	 * @throws Exception
	 */
	public static IValueConvert create(Field field, Class<?> columnClass, Class<?> fieldClass,SqlDriver driver) throws Exception {
		// 转化成这样
		ColumnConvert convert = field.getAnnotation(ColumnConvert.class);
		if (convert != null) {
			// 首先比较数据库中的class是否和targetclass相等
			Class<?> targetClass = convert.target();
			Class<? extends IValueConvert> convertClass = convert.toEntity();
			if(ClassUtil.isEqual(columnClass, targetClass)){
				return convertClass.newInstance();
			}
		}
		return ValueConvertFactory.create(columnClass, fieldClass);
	}
	
	private static IValueConvert createValueConver(IValueConvert target,Class<? extends IValueConvert> convertClass){
		
		IValueConvert valueConvert = CachedClassUtil.newInstance(convertClass);
		if(target!=null){
			return new BindConvert(target, valueConvert);
		}
		return valueConvert;
	}
	private static IValueConvert createValueConver(IValueConvert valueConvert, ColumnConvert convert) {
		if(convert==null){
			return valueConvert;
		}
		
		return createValueConver(valueConvert,convert.toEntity());
	}
	
	

}
